<template>
  <!-- 条件查询 -->
     <el-form :inline="true" :model="formInline" class="demo-form-inline">
    <el-form-item label="编号">
      <el-input v-model="formInline.Warehouse_Number" placeholder="请输入编号" clearable />
    </el-form-item>
     <el-form-item label="仓库名称">
      <el-input v-model="formInline.Warehouse_Name" placeholder="请输入仓库名称" clearable />
    </el-form-item>
    <el-form-item label="部门">
      <el-select
        v-model="formInline.Department_ID"
        placeholder="请选择"
        clearable
        class="warehouse-select"
      >
        <el-option v-for="item in deplarment" :label="item.department_Name" :value="item.id" />
       
      </el-select>
    </el-form-item>
    <el-form-item label="仓库类型">
      <el-select
        v-model="formInline.Warehouse_Type"
        placeholder="请选择"
        clearable
        class="warehouse-select"
      >
        <el-option label="成品仓库一" value="成品仓库一" />
        <el-option label="成品仓库二" value="成品仓库二" />
        <el-option label="成品仓库三" value="成品仓库三" />
      </el-select>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="getdata()">查询</el-button>
    </el-form-item>
  </el-form>


   <!-- 页面数据 -->
  <el-button plain @click="AddWarehouse()">
新增
  </el-button>
    <el-button plain @click="handleExport()">
导出
  </el-button>
  
 <el-table :data="tableData" style="width: 100%">
  <el-table-column prop="warehouse_Number" label="仓库编号" width="100" />
    <el-table-column prop="warehouse_Name" label="仓库名称" width="100"  />
    <el-table-column prop="rental_Time" label="租赁时间" width="100" >
    <template v-slot="scoped">
    {{formatDate(scoped.row.rental_Time) }}
    </template>
    </el-table-column>  
    <el-table-column prop="warehouse_Type" label="仓库类型" width="100" />
    <el-table-column prop="department_Name" label="所属部门" width="100" />
    <!-- <el-table-column prop="state" label="是否禁用" width="100" /> -->
    <!-- 只读的"是否禁用"列 -->
    <el-table-column label="是否禁用">
      <template #default="scope">
        <el-checkbox
          v-model="scope.row.state" 
          disabled 
        class="custom-checkbox"
        />
      </template>
    </el-table-column>
    <!-- <el-table-column prop="default" label="是否默认" width="100" /> -->
     <!-- 只读的"是否默认"列 -->
    <el-table-column label="是否默认">
      <template #default="scope">
        <el-checkbox 
          v-model="scope.row.default" 
          disabled 
          class="custom-checkbox"
        />
      </template>
    </el-table-column>
    <el-table-column prop="address" label="地址" width="100" />
    <el-table-column prop="area" label="面积" width="100" />
    <el-table-column prop="contacts" label="联系人" width="100" />
    <el-table-column prop="phone" label="电话" width="100" />
     <el-table-column fixed="right" label="操作" width="250">
      <template #default="scoped">
        <el-button type="primary" @click="UpdateWarehouse(scoped.row.id)">编辑</el-button>
      <el-button type="danger" @click="del(scoped.row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <!-- 分页 -->
    <el-pagination
      v-model:current-page="page.PageIndex"
      v-model:page-size="page.PageSize"
      :page-sizes="[15, 20, 25, 30]"
      layout="total, sizes, prev, pager, next, jumper"
      prev-text="上一页"
      next-text="下一页"
      :total="page.totalCount"
    />

</template>

<script setup lang="ts">
import axios from 'axios'
import { reactive,onMounted, ref, watch } from 'vue'
import { BasicsRed } from '@/http/axiosHelper'
import { ElMessage, ElMessageBox } from 'element-plus'
import { BasicsWrite } from '@/http/axiosHelper'
import { useRouter } from 'vue-router'
import { statementRed } from '@/http/axiosHelper'
const router=useRouter();
const dialogVisible = ref(false)
function formatDate(dateStr: string) {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  if (isNaN(date.getTime())) return dateStr;
  const y = date.getFullYear();
  const m = String(date.getMonth() + 1).padStart(2, '0');
  const d = String(date.getDate()).padStart(2, '0');
  return `${y}-${m}-${d}`;
}
const AddWarehouse=()=>
{
  router.push('/AddWarehouse')
}

const UpdateWarehouse=(id:any)=>
{
  router.push({path:"/UpdateWarehouse",query:{id:id}})
}


const handleClose = (done: () => void) => {
  ElMessageBox.confirm('Are you sure to close this dialog?')
    .then(() => {
      done()
    })
    .catch(() => {
      // catch error
    })
}




const formInline = reactive({
  Warehouse_Type: '',
  Department_ID: '',
  Warehouse_Number: '',
  Warehouse_Name: '',
})

const page=reactive({
    PageIndex:1,
    PageSize:15,
    totalCount:0

})

// 导出函数（假设已配置 Axios 拦截器自动添加 Token）
async function handleExport() {
    try {
        // 1. 调用后端导出接口（GET 请求，参数通过 params 传递）
        const response = await BasicsRed({
            url: '/api/Warehouse/GetWarehouseExport', // 后端接口地址
            method: 'GET',
            params: {
                  PageIndex:page.PageIndex,
      PageSize:page.PageSize,
      Warehouse_Type:formInline.Warehouse_Type,
      Department_ID:formInline.Department_ID,
      Warehouse_Number:formInline.Warehouse_Number,
      Warehouse_Name:formInline.Warehouse_Name
            }, // 对应后端 [FromQuery] 的 command 参数
            responseType: 'blob', // 关键：指定响应类型为二进制流（Excel 文件）
        });

        // 2. 从响应头获取文件名（后端通过 File 方法设置的 fileName）
        const fileName = getFileNameFromHeaders(response.headers);

        // 3. 生成下载链接并触发下载
        const blob = new Blob([response.data], {
            type: response.headers['content-type'] || 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = fileName; // 文件名从响应头获取或自定义
        document.body.appendChild(a);
        a.click();

        // 4. 清理资源
        window.URL.revokeObjectURL(url);
        document.body.removeChild(a);

    } catch (error: any) {
        // 处理错误（如后端返回 401/400 等）
        console.error('导出失败：', error.response?.data || error.message);
        alert('导出失败，请检查参数或重新登录');
    }
}


// 辅助函数：从响应头提取文件名（后端通过 File 方法设置）
function getFileNameFromHeaders(headers: any) {
    const contentDisposition = headers['content-disposition'] || headers['Content-Disposition'];
    if (!contentDisposition) return '仓库管理.xlsx'; // 默认文件名

    // 解码文件名（处理中文编码问题）
    const match = contentDisposition.match(/filename\*?=([^;]+)/);
    if (match) {
        return decodeURIComponent(match[1].replace(/["']/g, ''));
    }
    return '仓库管理.xlsx';
}

const page2=reactive({
    PageIndex:1,
    PageSize:100,
    totalCount:0

})
watch(page,()=>
{
  getdata();
})
onMounted(()=>
{
    delparmentdata();
    getdata();
})


const del=(id:any)=>
{

ElMessageBox.confirm(
    '确认删除吗?',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
     BasicsWrite.put("/api/Warehouse/DelwarehouseHandle",{id:id}).then(res=>
{
   if(res.data.code==200)
   {
    ElMessage.success("删除成功");
    getdata();
   }
   else
   {
    ElMessage.success("删除失败");
   }
}
)
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消',
      })
    })




}

const deplarment=ref()
const delparmentdata=()=>
{
    BasicsRed.get("/api/Deparment/GetDepartmentHandle",{params:{PageIndex:page2.PageIndex,PageSize:page2.PageSize}}).then(res=>
        {
            deplarment.value=res.data.data
        }
    )
}

const tableData=ref([]);

const getdata=()=>
{
    BasicsRed.get("/api/Warehouse/GetWarehouseHandle",{params:{
      PageIndex:page.PageIndex,
      PageSize:page.PageSize,
      Warehouse_Type:formInline.Warehouse_Type,
      Department_ID:formInline.Department_ID,
      Warehouse_Number:formInline.Warehouse_Number,
      Warehouse_Name:formInline.Warehouse_Name
    
    }}).then(res=>
        {
tableData.value=res.data.data
page.totalCount=res.data.totalCount
        }
    )
}



const onSubmit = () => {
  console.log('submit!')
}
</script>

<style scoped>
.demo-form-inline .el-input {
  --el-input-width: 120px;
}

.demo-form-inline .el-select {
  --el-select-width: 120px;
}

/* 下拉框宽度样式 */
.warehouse-select {
  min-width: 200px;
  width: 100%;
}

.warehouse-select :deep(.el-input__wrapper) {
  min-width: 200px;
}

.warehouse-select :deep(.el-input__inner) {
  min-width: 200px;
}
/* 调整只读复选框的样式 */
.readonly-checkbox {
  cursor: default !important;
  .el-checkbox__input {
    cursor: default !important;
    .el-checkbox__inner {
      cursor: default !important;
    }
  }
  .el-checkbox__label {
    cursor: default !important;
  }
}

/* 自定义复选框选中样式，让选中更明显 */
.custom-checkbox {
  /* 未选中状态 */
  .el-checkbox__inner {
    border: 2px solid #dcdfe6; /* 边框加粗 */
    background: #fff;
  }
  /* 选中状态 */
  .el-checkbox__input.is-checked .el-checkbox__inner {
    background-color: #409eff; /* 选中背景色 */
    border-color: #409eff;     /* 选中边框色 */
    transform: scale(1.1);     /* 选中时稍微放大，突出显示 */
  }
  /* 对勾样式优化 */
  .el-checkbox__input.is-checked .el-checkbox__inner::after {
    width: 6px;
    height: 12px;
  }
  /* 禁用状态下，也保持选中样式清晰 */
  .el-checkbox.is-disabled.is-checked .el-checkbox__inner {
    background-color: #c0c4cc;
    border-color: #c0c4cc;
  }
}

</style>